import EntityAnimCtl from "./EntityAnimCtl";
import EffectAnimCtl  from "./../models/EffectAnimCtl";
import FirstPlayerMoveCtl from "./../models/FirstPlayerMoveCtl";
import * as Def from "./../consts/Def";


export default class FirstPlayerCtl extends Laya.Script3D {
    constructor() { super(); }

    protected _animCtl:EntityAnimCtl;

    protected _moveCtl:FirstPlayerMoveCtl;

    protected _sprite:Laya.Sprite3D;

    protected _effectBook = {};

    public onAwake():void{
        this._animCtl = this.owner.getComponent(EntityAnimCtl);
        this._moveCtl = this.owner.getComponent(FirstPlayerMoveCtl);
        this._sprite = this.owner as Laya.Sprite3D;
    }


    public onUpdate():void{
        this._undateMotion();
        this._removeUnliveEffects();
    }

    protected _undateMotion():void{
        var motion = this._animCtl.getMotion();
        if(this._moveCtl.moving){
            if(motion != Def.MotionType.run){
                this._animCtl.doMotion(Def.MotionType.run);
            }
        }
        else{
            if(motion == Def.MotionType.run){
                this._animCtl.doMotion(Def.MotionType.idle);
            }
        }

        if(motion != Def.MotionType.attacka){
            this._moveCtl.freeze = false;
        }
    }

    protected _removeUnliveEffects():void{
         let delList = new Array<Laya.Sprite3D>();
         this._doingEffects.forEach(element => {
             let ctl = element.getComponent(EffectAnimCtl) as EffectAnimCtl;
 
             if(!ctl.isAlive){
                 delList.push(element);
             }
         });
 
         delList.forEach(element =>{
             this._doingEffects.splice(this._doingEffects.indexOf(element), 1);
             element.destroy(true);
         });
    }

    public onDestroy():void{

    }

    public onKeyDown(e: Laya.Event): void{
        switch(e.keyCode){
            case Laya.Keyboard.SPACE:
                this._animCtl.doMotion(Def.MotionType.attacka);
                this._moveCtl.freeze = true;
                this.spell(0);
                break;
        }
    }

    public registEffectUrl(skillId:number, url:string){
        this._effectBook[skillId] = url;
    }

    public getEffectUrl(skillId:number):string{
        return this._effectBook[skillId];
    }

    protected _doingEffects:Array<Laya.Sprite3D> = [];

    public spell(skillId:number):void{

        var effectUrl = this.getEffectUrl(skillId);

        let position = this._sprite.transform.position;

        let template = Laya.loader.getRes(effectUrl) as Laya.Sprite3D;

        let effect = template.clone() as Laya.Sprite3D;
        effect.transform.translate(position);

        this.owner.scene.addChild(effect) as Laya.Sprite3D;

        let effectCtl = effect.addComponent(EffectAnimCtl) as EffectAnimCtl;
        effectCtl.play();
        this._doingEffects.push(effect);
    }
}

